package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjFactoryAccount;
import com.zb.mapper.ZjFactoryAccountMapper;
import com.zb.secure.BCryptUtil;
import com.zb.service.ZjFactoryAccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 厂商账号表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-02-27
 */
@Service
public class ZjFactoryAccountServiceImpl extends ServiceImpl<ZjFactoryAccountMapper, ZjFactoryAccount> implements ZjFactoryAccountService {
    @Resource
    private ZjFactoryAccountMapper factoryAccountMapper;

    // 根据手机号获取品牌商家账号
    @Override
    public Object getByPhone(String phone) {
        QueryWrapper<ZjFactoryAccount> wrapper = new QueryWrapper<>();
        wrapper.select("id", "phone", "name")
                .eq("phone", phone);
        ZjFactoryAccount account = this.getOne(wrapper);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existPhone", null != account);
        resultMap.put("id", null != account? account.getId() : 0);
        resultMap.put("phone", null != account? account.getPhone() : "");
        resultMap.put("username", null != account? account.getName() : "");
        return resultMap;
    }

    // 保存品牌厂商账号
    @Override
    public Long save(Long id, String phone, String username) {
        ZjFactoryAccount account = null;
        if (null != id && id > 0) {
            account = this.getById(id);
            if (!Objects.equals(username, account.getName())) {
                account.setName(username);
                this.updateById(account);
            }
            return account.getId();
        }
        account = factoryAccountMapper.getByPhone(phone);
        if (null != account) {
            if (!Objects.equals(username, account.getName())) {
                account.setName(username);
                this.updateById(account);
            }
            return account.getId();
        }
        account = new ZjFactoryAccount();
        account.setId(IdWorker.getId());
        account.setAccount("ZB_" + BCryptUtil.generatorSalt().substring(10, 20));
        account.setPhone(phone);
        account.setSalt(BCryptUtil.generatorSalt());
        account.setPassword(BCryptUtil.encryPassword(BCryptUtil.MD5(phone.substring(5)), account.getSalt()));
        account.setName(username);
        account.setNickname("ZBDD-"+phone.substring(6));
        account.setAvatar("");
        account.setStatus(0);
        this.save(account);
        return account.getId();
    }
}
